<template>
	<div class="external-api-connector-form">
		<a-form ref="formRef" :model="modelValue" :rules="rules" layout="vertical">
			<!-- 基础配置 -->
			<a-divider orientation="left">基础配置</a-divider>
			<BasicConfigForm ref="basicConfigRef" v-model:modelValue="basicConfig" @change="handleBasicConfigChange" />

			<!-- 认证配置 -->
			<a-divider orientation="left">认证配置</a-divider>
			<AuthConfigForm ref="authConfigRef" v-model:modelValue="authConfig" @change="handleAuthConfigChange" />

			<!-- API接口配置 -->
			<a-divider orientation="left">API接口配置</a-divider>
			<ApiListConfig
				ref="apiListConfigRef"
				v-model:modelValue="apiList"
				:baseUrl="basicConfig.baseUrl"
				@change="handleApiListChange"
			/>
		</a-form>

		<!-- 连接测试 -->
		<a-divider />
		<a-space>
			<a-button :loading="testing" type="primary" @click="testConnection">
				<template #icon>
					<CheckCircleOutlined />
				</template>
				测试连接
			</a-button>
			<a-button :loading="previewing" @click="previewApis">
				<template #icon>
					<EyeOutlined />
				</template>
				预览API列表
			</a-button>
		</a-space>

		<!-- API预览模态框 -->
		<a-modal v-model:open="previewModalVisible" :footer="null" title="API接口预览" width="80%">
			<a-table
				:columns="previewColumns"
				:data-source="previewApiList"
				:loading="previewing"
				:pagination="{ pageSize: 10 }"
				size="small"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'method'">
						<a-tag :color="getMethodColor(record.method)">
							{{ record.method }}
						</a-tag>
					</template>
					<template v-if="column.dataIndex === 'fullUrl'">
						<a-typography-text copyable>{{ record.fullUrl }}</a-typography-text>
					</template>
				</template>
			</a-table>
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, reactive, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { CheckCircleOutlined, EyeOutlined } from '@ant-design/icons-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import BasicConfigForm from './components/BasicConfigForm.vue'
	import AuthConfigForm from './components/AuthConfigForm.vue'
	import ApiListConfig from './components/ApiListConfig.vue'

	// Props
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	// Emits
	const emit = defineEmits(['update:modelValue', 'change'])

	// 表单引用
	const formRef = ref()
	const basicConfigRef = ref()
	const authConfigRef = ref()
	const apiListConfigRef = ref()

	// 表单验证规则
	const rules = {
		baseUrl: [{ required: true, message: '请输入API基础地址', trigger: 'blur' }]
	}

	// 获取配置数据的辅助函数
	const getConfigValue = (key, defaultValue) => {
		const config = props.modelValue.config || {}
		return config[key] || defaultValue
	}

	// 配置数据
	let basicConfig = reactive({
		baseUrl: getConfigValue('baseUrl', ''),
		timeout: getConfigValue('timeout', '30000'),
		retryCount: getConfigValue('retryCount', '3')
	})

	let authConfig = reactive({
		authType: getConfigValue('authType', 'BEARER_TOKEN'),
		auth_token: getConfigValue('auth_token', ''),
		auth_prefix: getConfigValue('auth_prefix', 'Bearer '),
		auth_apiKey: getConfigValue('auth_apiKey', ''),
		auth_keyName: getConfigValue('auth_keyName', 'X-API-Key'),
		auth_location: getConfigValue('auth_location', 'header'),
		auth_username: getConfigValue('auth_username', ''),
		auth_password: getConfigValue('auth_password', '')
	})

	const apiList = ref([])

	// 测试状态
	const testing = ref(false)
	const previewing = ref(false)

	// API预览
	const previewModalVisible = ref(false)
	const previewApiList = ref([])

	// 初始化API列表
	const initApiList = () => {
		try {
			const config = props.modelValue.config || {}
			const apisConfig = config.apis
			if (apisConfig) {
				apiList.value = JSON.parse(apisConfig)
			} else {
				apiList.value = []
			}
		} catch (error) {
			console.error('解析API配置失败:', error)
			apiList.value = []
		}
	}

	// 监听配置变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal.config) {
				const config = newVal.config

				Object.assign(basicConfig, {
					baseUrl: config.baseUrl || '',
					timeout: config.timeout || '30000',
					retryCount: config.retryCount || '3'
				})

				Object.assign(authConfig, {
					authType: config.authType || 'BEARER_TOKEN',
					auth_token: config.auth_token || '',
					auth_prefix: config.auth_prefix || 'Bearer ',
					auth_apiKey: config.auth_apiKey || '',
					auth_keyName: config.auth_keyName || 'X-API-Key',
					auth_location: config.auth_location || 'header',
					auth_username: config.auth_username || '',
					auth_password: config.auth_password || ''
				})

				initApiList()
			}
		},
		{ deep: true, immediate: true }
	)

	// 更新配置
	const updateConfig = () => {
		const config = {
			...basicConfig,
			...authConfig,
			apis: JSON.stringify(apiList.value)
		}

		const updatedValue = {
			...props.modelValue,
			config
		}

		emit('update:modelValue', updatedValue)
		emit('change', updatedValue)
	}

	// 处理基础配置变化
	const handleBasicConfigChange = (config) => {
		Object.assign(basicConfig, config)
		updateConfig()
	}

	// 处理认证配置变化
	const handleAuthConfigChange = (config) => {
		Object.assign(authConfig, config)
		updateConfig()
	}

	// 处理API列表变化
	const handleApiListChange = (list) => {
		apiList.value = list
		updateConfig()
	}

	// 测试连接
	const testConnection = async () => {
		try {
			testing.value = true

			// 构建测试配置
			const testConfig = {
				type: 'EXTERNAL_API',
				config: {
					...basicConfig,
					...authConfig,
					apis: JSON.stringify(apiList.value)
				}
			}

			await dataConnectorApi.testConnection(testConfig)
			message.success('外部API连接器测试成功！')
		} catch (error) {
			console.error('连接测试失败:', error)
			message.error('连接测试失败：' + (error.message || '未知错误'))
		} finally {
			testing.value = false
		}
	}

	// 预览API列表
	const previewApis = async () => {
		if (apiListConfigRef.value?.previewApis) {
			apiListConfigRef.value.previewApis()
		}
	}

	// 表单验证
	const validate = async () => {
		try {
			await formRef.value.validate()

			// 验证子组件
			if (basicConfigRef.value?.validateConfig) {
				const basicValidation = basicConfigRef.value.validateConfig()
				if (!basicValidation.valid) {
					message.error(basicValidation.message)
					return false
				}
			}

			return true
		} catch (error) {
			return false
		}
	}

	// 暴露方法给父组件
	defineExpose({
		validate
	})
</script>

<style scoped>
	.external-api-connector-form {
		padding: 16px;
	}

	.form-help-text {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
	}

	:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
		margin: 16px 0;
	}

	.mt-2 {
		margin-top: 8px;
	}
</style>
